/** ****************************************************************************
@addtogroup SWITCH
@{
*******************************************************************************/

#include "dimmer.h"

void dimmer_init(driver_dimmer_t* dev, FUNC_GPIO_PwmSetDuty funcPwmSetDuty) {
	if(!dev) { return; }
	dev->funcPwmSetDuty	= funcPwmSetDuty;
	dev->duty = 0;
	dev->blinkTaskId = NULL;
	dev->blinkExOnTime = 0;
}

bool dimmer_switchTo(driver_dimmer_t* dev, switch_state_t state, uint32_t keepTime1, uint32_t keepTime2, uint8_t flashTimes) {
	if(!dev) { return false; }
	
    // 如果之前已经调过 blinkEx() ，则取消之前的
    dimmer_blinkStop(dev);

    if(state == SWITCH_OFF) {
        return dimmer_off(dev);
    } else if(state == SWITCH_ON) {
        return dimmer_on(dev);
    } else if(state == SWITCH_TOGGLE) {
        dimmer_toggle(dev);
		return true;
    } else if(state == SWITCH_BLINK) {
        dimmer_blinkEx(dev, keepTime1, keepTime2, flashTimes);
    }
    return false;
}

static void blinkHandler(uint8_t len, void* data) {
	if(!len || !data) { return; }
	driver_dimmer_t* dev = (driver_dimmer_t*)getPointer(data);
	dimmer_off(dev);
}

void dimmer_blink(driver_dimmer_t* dev, uint16_t time) {
	if(!dev) { return; }
	dimmer_on(dev);
	osTaskRunAfter(time, blinkHandler, sizeof(void*), &dev);
}

static void blinkExHandler(uint8_t len, void* data) {
	if(!len || !data) { return; }
	driver_dimmer_t* dev = (driver_dimmer_t*)getPointer(data);
	dimmer_blink(dev, dev->blinkExOnTime);
}

uint16_t dimmer_blinkEx(driver_dimmer_t* dev, uint16_t onTime, uint16_t offTime, uint16_t count) {
	// 参数检查
	if(!(dev && onTime && offTime && count>1)) { return NULL; }
    dev->blinkExOnTime = onTime;

    // 如果之前已经调过 blinkEx()，则取消之前的
    osTaskDestroy(dev->blinkTaskId);

    // 先闪第一次
    dimmer_blink(dev, onTime);
    if(count != OSTASK_REPEAT_FOREVER) { count--; }

	// 安排后续的闪烁
	// 注意：需要把对象的指针传过去，以便在回调函数中访问对象
	return dev->blinkTaskId = osTaskRunEvery(onTime+offTime, count, blinkExHandler, sizeof(dev), &dev);
}


/// @}
